package com.puyuba.puyuba.view.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.puyuba.puyuba.R;
import com.puyuba.puyuba.SkinApplication;
import com.puyuba.puyuba.view.activity.UserEditActivity;
import com.pyb.java.basemodule.BaseFragment;
import com.puyuba.puyuba.bean.CustomerLevelBean;
import com.puyuba.puyuba.bean.FindPriListBean;
import com.puyuba.puyuba.network.BaseApis;
import com.pyb.java.cache.CacheUserInfo;
import com.pyb.java.cache.SPHelper;
import com.pyb.java.cache.bean.UserInfoBean;
import com.pyb.java.commonutil.utils.FileUtils;
import com.pyb.java.network.ResponseEntity;
import com.pyb.java.network.RetrofitManger;
import com.pyb.java.network.observers.ResponseObserve;

import com.pyb.java.network.scheduler.RxSchedulers;
import com.puyuba.puyuba.network.UserApi;
import com.pyb.java.commonutil.utils.NetUtil;
import com.pyb.java.commonutil.ToastHelper;
import com.puyuba.puyuba.view.activity.MainWebActivity;
import com.puyuba.puyuba.view.adapter.FindPrivateAdatper;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.disposables.Disposable;

/**
 * 私有库页面
 */

public class FindPrivateFragment extends BaseFragment implements OnRefreshLoadMoreListener {

    private RefreshLayout mSmartRefreshLayout;
    private RecyclerView mRecyclerView;

    private FindPrivateAdatper mAdapter;
    private String orderTabType;
    private List<FindPriListBean.DataBean> data;
    private List<CustomerLevelBean> listData;
    private ArrayList<String> customlist = new ArrayList<>();
    private String name;
    private UserInfoBean userInfoBean;
    private String mobile;

    public static FindPrivateFragment getInstance(String type) {
        FindPrivateFragment findTabListFragment = new FindPrivateFragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        findTabListFragment.setArguments(args);
        return findTabListFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_find_private;
    }

    @Override
    public void initView(View view) {
        mSmartRefreshLayout = (RefreshLayout) view.findViewById(R.id.mSmartRefreshLayout_private);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.fragment_find_private);

        if (null != getArguments()) {
            orderTabType = getArguments().getString("type");
        }

        mSmartRefreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        mSmartRefreshLayout.setOnRefreshListener(refreshlayout -> {
            boolean mobileConnected = NetUtil.isNetworkAvailable(SkinApplication.sContext);
            if (mobileConnected) {
                initData(userInfoBean.getUser().getCrm_user_id(),"");
            } else {
                ToastHelper.showToast("网络未连接，请检查网络状态");
                if (mSmartRefreshLayout!= null){
                    mSmartRefreshLayout.finishRefresh();
                }
            }
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        //为RecyclerView设置分割线(这个可以对DividerItemDecoration进行修改，自定义)
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        //动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mAdapter = new FindPrivateAdatper(R.layout.fragment_find_private_item);
        mAdapter.bindToRecyclerView(mRecyclerView);

//        mAdapter.setEmptyView(R.layout.layout_takefood_list_empty);

        userInfoBean = CacheUserInfo.getInstance().getsUserInfo();

    }

    public void initData(int crmuserid,String name){
        showLoadingDialog();
        RetrofitManger.getInstance().createService(UserApi.class)
                .getprilist(crmuserid,name)
                .compose(RxSchedulers.<ResponseEntity<FindPriListBean>>applySchedulers())
                .subscribe(new ResponseObserve<FindPriListBean>() {

                    @Override
                    public void onSuccess(ResponseEntity<FindPriListBean> responseEntity) {
                        data = responseEntity.getData().getData();

                        mAdapter.setNewData(data);
                        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                            @Override
                            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                switch (view.getId()) {
                                    case R.id.tv_user_info:
                                        FindPriListBean.DataBean dataBean = mAdapter.getData().get(position);
                                        UserEditActivity.startActivity(getContext(),dataBean);
                                        break;
                                    case R.id.tv_contact_users:
                                        mobile = mAdapter.getData().get(position).getMobile();
                                        checkcallPermission(mobile);
                                        break;
                                }
                            }
                        });

                    }

                    @Override
                    public void onFail(String errorMsg) {
                        if (errorMsg != null&&!errorMsg.equals("")){
                            ToastHelper.show(errorMsg);
                        }else {
                            ToastHelper.show("服务器繁忙，请稍后再试");
                        }
                    }

                    @Override
                    public void onSubscribeStart(@io.reactivex.annotations.NonNull Disposable disposable) {
                        addDisposable(disposable);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        closeLoadingDialog();
                        if (mSmartRefreshLayout!= null){
                            mSmartRefreshLayout.finishRefresh();
                        }
                    }
                });
    }

    private void checkcallPermission(String phone) {

        if (FileUtils.isHasSimCard(SkinApplication.getInstance())) {
            if (!(getContext().checkSelfPermission(Manifest.permission.MANAGE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    //拨打老师电话
                    XXPermissions.with(getContext())
                            // 申请单个打电话权限
                            .permission(Permission.CALL_PHONE)
                            .request(new OnPermissionCallback() {

                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    if (all) {
                                        //toast("获取录音和日历权限成功");
                                        callPhone(phone);
                                    } else {
                                        //"获取部分权限成功，但部分权限未正常授予");
                                    }
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    if (never) {
                                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                        XXPermissions.startPermissionActivity(SkinApplication.getInstance(), permissions);
                                    } else {
                                        //toast("获取录音和日历权限失败");
                                    }
                                }
                            });
                }
            } else {
                callPhone(phone);
            }
        } else {
            ToastHelper.show("当前设备未插SIM卡~");
        }
    }

    /**
     * 拨打电话
     */
    public void callPhone(String phone) {
        if (phone == null) {
            ToastHelper.show("请重新获取数据");
            return;
        }

        Intent Intent = new Intent(android.content.Intent.ACTION_DIAL,
                Uri.parse("tel:" + phone));//跳转到拨号界面，同时传递电话号码
        getContext().startActivity(Intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        initData(userInfoBean.getUser().getCrm_user_id(),"");
    }

    private void showPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(getContext(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
//               返回的分别是三个级别的选中位置
//                tvChooseGrade.setText(listData.get(options1).getKey()+listData.get(options1).getValue());
                initData(userInfoBean.getUser().getCrm_user_id(),"");
            }
        })
                .setTitleText("请选择需求分类")
                .setSelectOptions(0)//设置选择第一个
                .setOutSideCancelable(false)//点击背的地方不消失
                .build();//创建
        pvOptions.setPicker(customlist);
        pvOptions.show();

    }

    private void initCustomerlevelData(){
        RetrofitManger.getInstance().createService(UserApi.class)
                .getcustomerlevel()
                .compose(RxSchedulers.<ResponseEntity<List<CustomerLevelBean>>>applySchedulers())
                .subscribe(new ResponseObserve<List<CustomerLevelBean>>() {

                    @Override
                    public void onSuccess(ResponseEntity<List<CustomerLevelBean>> responseEntity) {
                        listData = responseEntity.getData();

                        customlist = new ArrayList<>();
                        for (CustomerLevelBean customerLevelBean : listData){
                            customlist.add(customerLevelBean.getKey()+customerLevelBean.getValue());
                        }
                        showPickerView();
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        if (errorMsg != null&&!errorMsg.equals("")){
                            ToastHelper.show(errorMsg);
                        }else {
                            ToastHelper.show("服务器繁忙，请稍后再试");
                        }
                    }

                    @Override
                    public void onSubscribeStart(@io.reactivex.annotations.NonNull Disposable disposable) {
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

    }
}
